package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Game;
import model.GameManager;
import model.Player;
import model.PlayerDao;

/**
 * Servlet implementation class SessionController
 */
public class LobbyController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	GameManager gameManager;
	PlayerDao playerDao;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LobbyController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		RequestDispatcher view = request.getRequestDispatcher("Lobby.jsp");
		gameManager = (GameManager)getServletContext().getAttribute("gameManager");
		ArrayList<Game> games = gameManager.getJoinableGames();
		
		// Refreshen van games-lijst
		try {
			if(((String)request.getParameter("refresh")).equals("now")) {
				view = request.getRequestDispatcher("Lobby.jsp");
				view.forward(request, response);
			}
		}
		catch(Exception e) {
//			e.printStackTrace();
		}
		
		// Poging tot joinen van game
		if(request.getParameter("goToGame") != null) {
			boolean clone = false;
			for(Game g : games) {
				if(request.getParameter("goToGame").equals(g.getName())) {
					for(Player pl : g.getPlayers()) {
						if(pl.getName().equals(((Player)session.getAttribute("player")).getName())) {
							clone = true;
						}
					}
					if(!clone) {
						view = request.getRequestDispatcher("/WEB-INF/pages/Table.jsp");
						Player player = (Player)session.getAttribute("player");
						player.setSession(session.getId());
						session.setAttribute("game", g.getName());
						gameManager.joinGame(g.getName(), player);
						if(g.getPlayers().size() == 4) {
							g.startGame();
							System.out.println("Spel zit vol! Spel gestart...");
						}
					} else { break; }
				}
			}
			view.forward(request, response);
		}
		//Uitloggen
		if(request.getParameter("log") != null) {
			session.invalidate();
			view = request.getRequestDispatcher("Lobby.jsp");
			view.forward(request, response);
		}
		try {
			if(request.getParameter("action").equals("check")) {
				//Check inbouwen op speler wel aan de beurt is
				Game currentGame = (Game)session.getAttribute("game");
				currentGame.check();
			}
		}
		catch(Exception e) {
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		RequestDispatcher view = request.getRequestDispatcher("Lobby.jsp");
		gameManager = (GameManager)getServletContext().getAttribute("gameManager");
		playerDao = (PlayerDao)getServletContext().getAttribute("playerDao");
		
		// Poging tot registreren
		if(request.getParameter("username") != null) {
			view = request.getRequestDispatcher("Register.jsp");
			if(request.getParameter("password1").equals(request.getParameter("password2"))) {
				if((request.getParameter("username").length() > 3) && (request.getParameter("password1").length() > 3)) {
					boolean succes = playerDao.newUser(request.getParameter("username"), request.getParameter("password1"));
					//TODO: Checken of user niet al bestaat. Zo niet: nieuwe user aanmaken en gebruik inloggen.
					if(succes) {
						Player player = new Player(request.getParameter("username"));
						session.setAttribute("player", player);
						view = request.getRequestDispatcher("Lobby.jsp");
					}
				}
			}
			
		}
		// Poging tot inloggen
		if(request.getParameter("name") != null) {
			boolean correct = new PlayerDao().checkUser(request.getParameter("name"), request.getParameter("password"));
			
			Player player = null;
			if(correct) {
				player = new Player(request.getParameter("name"));
			}
			
			view = request.getRequestDispatcher("Lobby.jsp");
			session.setAttribute("player", player);
		}
		// Poging tot aanmaken van game
		if(request.getParameter("gameName") != null) {
			boolean fout = false;
			if(request.getParameter("blind").equals("")) {
				fout = true;
			}
			else {
				try {
					Integer.parseInt(request.getParameter("blind"));
				} catch(Exception e) { fout = true; }
			}
			if(!fout) {
				Player player = (Player)session.getAttribute("player");
				player.setSession(session.getId());
				boolean exists = false;
				for(Game g : gameManager.getGames()) {
					if(g.getName().equals(request.getParameter("gameName"))) {
						exists = true;
						view = request.getRequestDispatcher("Lobby.jsp");
					}
				}
				if(!exists) {
					view = request.getRequestDispatcher("/WEB-INF/pages/Table.jsp");
	
					Game g = gameManager.newGame(request.getParameter("gameName"), player, Integer.parseInt(request.getParameter("blind")));
					session.setAttribute("game", g.getName());
				}
			}
			else {
				view = request.getRequestDispatcher("Lobby.jsp");
			}
		}
		view.forward(request, response);
	}
	
	// Games-lijst opbouwen
	public ArrayList<Game> getJoinableGames() {
		gameManager = (GameManager)getServletContext().getAttribute("gameManager");
		ArrayList<Game> games = gameManager.getJoinableGames();
		return games;
	}

}
